package com.daervin.svc.pipeline;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.common.constants.ImageType;
import com.daervin.svc.common.dto.img.DataItem;
import com.daervin.svc.common.utils.FileUtil;
import com.daervin.svc.dal.model.Image;
import com.daervin.svc.service.ImageService;
import org.springframework.util.CollectionUtils;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.ArrayList;
import java.util.List;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class ImgDaoPipeline implements Pipeline {

    private ImageService service;

    public ImgDaoPipeline(ImageService service) {
        this.service = service;
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        List<Image> list = new ArrayList<>();
        List<DataItem> newsList = resultItems.get(Constants.PARSER_RESULT);
        List<String> savedUrls = service.queryByType(ImageType.HU_XIU);
        int sort = 1;
        if (CollectionUtils.isEmpty(newsList)) {
            return;
        }
        FileUtil.dropAllFile(Constants.IMAGE_LOCALPATH);
        for (DataItem item : newsList) {
            if (savedUrls != null && savedUrls.contains(item.getOrigin_pic_path())) {
                continue;
            }
//            Calendar now = Calendar.getInstance();
//            String day = DateTimeUtils.longParse2(now.getTime());
//            String imgName = new StringBuilder(day).append("-").append(sort).append(".png").toString();
//            String localPath = Constants.IMAGE_LOCALPATH + imgName;
//            String domainUrl = Constants.IMAGE_DOMAIN + imgName;
//            boolean success = FileUtil.downloadSaveFile(item.getCover(), localPath);
//            if (!success) {
//                continue;
//            }
            Image po = new Image();
            po.setType(ImageType.HU_XIU.ordinal());
            po.setUrl(item.getPic_path());
            po.setFromUrl(item.getOrigin_pic_path());
            po.setSort(sort++);
            list.add(po);
        }

        if (service == null) {
            return;
        }
        service.bannerImg(list);
    }
}
